//
//  Controller.m
//  AddressBookToCSV
//
//  Created by Ken Ferry on Thu Jun 17 2004.
//  Copyright (c) 2004 Ken Ferry. All rights reserved.
//

#import "Controller.h"

#import <AddressBook/AddressBook.h>
#import "ABPerson+CSVExport.h"
#import "ABMultiValue+CSVExport.h"

@implementation Controller

- (IBAction)exportAddressBook:(id)sender
{
    NSSavePanel *savePanel = [NSSavePanel savePanel]; // NSSavePanel is 10.3
    
    [savePanel beginSheetForDirectory:NSHomeDirectory()
                                 file:@"contacts.csv"
                       modalForWindow:[self window]
                        modalDelegate:self
                       didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:) 
                          contextInfo:nil];
}

- (void)savePanelDidEnd:(NSSavePanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
    if (returnCode == NSOKButton)
    {
        [self exportAddressBookToFile:[sheet filename]];
    }
}


- (BOOL)exportAddressBookToFile:(NSString *)path
{
    NSData *csvDatabase = [self csvFormatAddressBook];
    
    return [csvDatabase writeToFile:path atomically:YES];
}

- (NSData *)csvFormatAddressBook
{
    NSEnumerator *allPeopleEnumerator = [[[ABAddressBook sharedAddressBook] people] objectEnumerator];
    return [self csvFormatDatabaseForPersonEnumerator:allPeopleEnumerator];
}

// testing only
- (NSData *)csvFormatDatabaseForTestGroup
{
    ABSearchElement *encodeTestSearchEl;
    ABGroup *encodeTestGroup;
    
    encodeTestSearchEl = [ABGroup searchElementForProperty:kABGroupNameProperty
                                                     label:nil 
                                                       key:nil 
                                                     value:@"Encode Test Group" 
                                                comparison:kABEqual];
    
    encodeTestGroup = [[[ABAddressBook sharedAddressBook] recordsMatchingSearchElement:encodeTestSearchEl] objectAtIndex:0];
    NSEnumerator *testPeopleEnumerator = [[encodeTestGroup members] objectEnumerator];
    
    return [self csvFormatDatabaseForPersonEnumerator:testPeopleEnumerator];
}

- (NSData *)csvFormatDatabaseForPersonEnumerator:(NSEnumerator *)personEnumerator
{
    NSMutableString *csvString;
    NSEnumerator *emailEnumerator;
    ABPerson *person;
    NSString *email;
    
    csvString = [NSMutableString stringWithString:@"Name,E-mail Address\n"];

    while (person = [personEnumerator nextObject])
    {        
        BOOL isCompany = [person isCompany];
        emailEnumerator = [[[person valueForProperty:kABEmailProperty] allValues] objectEnumerator];
        
        while (email = [emailEnumerator nextObject])
        {
            if (isCompany)
            {
                [csvString appendString:[NSString stringWithFormat:@"%@,%@\n", [person companyName], email]];
            }
            else
            {
                [csvString appendString:[NSString stringWithFormat:@"%@,%@\n", [person fullName], email]];
            }
        }
    }
    
    [csvString replaceOccurrencesOfString:@"(null)" 
                               withString:@"" 
                                  options:NSLiteralSearch 
                                    range:NSMakeRange(0, [csvString length])]; 
    
    return [csvString dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1) allowLossyConversion:YES];
}

@end
